package com.eportal.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysopt;
import com.eportal.domain.UsersCommunity;
import com.eportal.service.UsersCommunityService;

@Service("usersCommunityService")
public class UsersCommunityServiceImpl  implements UsersCommunityService{
	
	@Resource(name="dao")
	private BaseDAO dao;
	
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Override
	public UsersCommunity get(Long sid){
		UsersCommunity usersCommunity = (UsersCommunity)dao.getById(UsersCommunity.class, sid);
		return usersCommunity;
	}

	@Override
	public List<Map<String, String>> getByUserId(String userId,String agtCode, String communityId) {
		StringBuffer sb = new StringBuffer(""
				+ "select t.sid,t.communityid,t.score,c.communityname,c.citycode,c.street,b.cbname,i.cbname as installName  "
				+ "from T04_USERS_COMMUNITY t "
				+ "left join t03_community c on t.communityid =c.sid "
				+ "left join t02_agtent a on a.agtcode=c.agtcode "
				+ "left join t032_cinstallunit i on t.installunitId=i.sid "
				+ "left join t031_cbuilding b on i.cbuildingid=b.sid"
				+ " where t.status=1 and t.userid='");
		sb.append(userId);
		sb.append("'");
		int userRole =  (Integer) getSession().getAttribute("userRole");
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
		if (userRole == 21) {
			sb.append(" and a.sysoptid=");
			sb.append(user.getSid());
		}
		if (StringUtils.isNotBlank(agtCode)) {
			sb.append(" and c.agtCode='");
			sb.append(agtCode);
			sb.append("'");
		}
		if (StringUtils.isNotBlank(communityId)) {
			sb.append(" and t.communityid='");
			sb.append(communityId);
			sb.append("'");
		}
	    return dao.queryBySql(sb.toString());
	}

	@Override
	public UsersCommunity getByWhere(String where) {
		StringBuffer sb = new StringBuffer("from UsersCommunity where ");
		sb.append(where);
		return (UsersCommunity) dao.loadObject(sb.toString());
	}

	@Override
	public UsersCommunity add(UsersCommunity usersCommunity) throws Exception {
		dao.save(usersCommunity);
        return usersCommunity;
	}

	@Override
	public void update(UsersCommunity usersCommunity) {
		 dao.update(usersCommunity);
	}
	
	
	
}
